package com.example.user_manage.Component;

import com.example.user_manage.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义退出登录处理器
 */
@Slf4j
@Component
@AllArgsConstructor
public class MyLogoutHandler implements LogoutSuccessHandler {

    /**
     * 模拟redis
     */
    private final MyRedis myRedis;

    /**
     * 退出登录时调用该方法
     * @param request 请求对象
     * @param response 响应对象
     * @param authentication 身份验证对象
     * @throws IOException IO异常
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException{
        //指定响应的格式和字符集编码格式
        response.setContentType("application/json;charset=utf-8");
        //获取用户信息
        User user = (User) authentication.getPrincipal();
        log.info("用户“{}“退出登录，清理token缓存", user.getUsername());
        myRedis.myRedis.remove(user.getId().toString());
        //发出响应
        response.getWriter().write("退出成功");
    }
}
